package com.agent.web;

import com.agent.entity.Dict;
import com.agent.page.EasyuiPage;
import com.agent.service.IDictService;
import com.agent.shiro.ShiroUser;
import com.agent.util.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;


@Controller
@RequestMapping("/dict")
@Slf4j
public class DictController {
    @Autowired
    private IDictService dictService;


    @RequestMapping(method = RequestMethod.GET)
    public String toHtml() {
        return "system/dict";
    }


    @RequestMapping("/list")
    @ResponseBody
    public EasyuiPage getDictList(Integer page, Integer rows, Dict dict) {
        EasyuiPage<Dict> searchDict = dictService
                .searchDict(page,rows,dict);
        return searchDict;

    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> insert(Dict dict, BindingResult result, HttpServletRequest request) {
        dict.setUpdateTime(new Date());
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        dict.setUpdator(shiroUser.getUserName());
        dictService.insert(dict);
        return ResponseData.getSuccessResult();
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(Dict dict, @PathVariable("id") Integer id) {
        dict.setId(id);
        dict.setUpdateTime(new Date());
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        dict.setUpdator(shiroUser.getUserName());
        try{
            dictService.update(dict);
            return ResponseData.getSuccessResult();
        }catch (Exception e){
            log.error("com.agent.web.DictController.update error |",e);
            return ResponseData.getErrorResult("更新失败");
        }
    }


}
